<template>
  <div class="app">
    <!-- 上部：文件打印模块 -->
    <a-card :bordered="false" :hoverable="true" class="print-card">
      <div class="print-title">文件打印</div>

      <a-form
        ref="printFormRef"
        class="print-form"
        layout="vertical"
        :model="printForm"
      >
        <a-row :gutter="24">
          <!-- 文件上传区域 -->
          <a-col :span="6">
            <a-form-item
              label="选择文件"
              name="file"
              :rules="[{ required: true, message: '请选择要打印的文件' }]"
            >
              <FileUpload
                list-type="text"
                accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
                :maxUploadSize="50"
                buttonText="选择文件"
                :defaultFileList="fileList"
                :multiple="false"
                :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
                @change="handleFileUpload"
              />
              <div class="upload-hint">支持PDF、Word、Excel、PPT格式</div>
            </a-form-item>
          </a-col>

          <!-- 打印机选择 -->
          <a-col :span="6">
            <a-form-item
              label="选择打印机"
              name="printerId"
              :rules="[{ required: true, message: '请选择打印机' }]"
            >
              <a-select
                v-model:value="printForm.printerId"
                placeholder="请选择打印机"
                style="width: 100%"
                :loading="loadingPrinters"
              >
                <a-select-option :value="item" v-for="item in printerList" :key="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <!-- 打印份数 -->
          <a-col :span="6">
            <a-form-item
              label="打印份数"
              name="copies"
              :rules="[
                { required: true, message: '请输入打印份数' },
                { type: 'number', min: 1, max: 100, message: '打印份数必须在1-100之间' }
              ]"
            >
              <a-input-number
                v-model:value="printForm.copies"
                :min="1"
                :max="100"
                :precision="0"
                placeholder="请输入份数"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>

          <!-- 打印按钮 -->
          <a-col :span="6" class="print-button-col">
            <a-form-item>
              <a-button
                type="primary"
                @click="handleSubmit"
                :loading="printing"
                class="print-button"
              >
                <PrinterOutlined /> 开始打印
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 下部：打印记录模块 -->
    <a-card :bordered="false" :hoverable="true" class="record-card">
      <!-- 表格操作行和搜索区域 -->
      <a-row class="smart-table-btn-block" :gutter="16">
        <a-col :flex="1">
          <a-button-group>
            <a-button @click="refreshRecords" type="primary">
              <ReloadOutlined /> 刷新记录
            </a-button>
            <a-button @click="resetSearch" type="default">
              <ClearOutlined /> 重置
            </a-button>
          </a-button-group>
        </a-col>

        <!-- 搜索区域 -->
        <a-col :flex="2">
          <a-row :gutter="16" type="flex" align="middle">
            <a-col :span="10">
              <a-input
                v-model:value="searchForm.createBy"
                placeholder="请输入打印人"
                allow-clear
                @pressEnter="handleSearch"
              />
            </a-col>
            <a-col :span="10">
              <a-input
                v-model:value="searchForm.fileName"
                placeholder="请输入文件名称"
                allow-clear
                @pressEnter="handleSearch"
              />
            </a-col>
            <a-col :span="4">
              <a-button type="primary" @click="handleSearch">
                <SearchOutlined /> 搜索
              </a-button>
            </a-col>
          </a-row>
        </a-col>

        <div class="smart-table-setting-block">
          <TableOperator v-model="columns" :tableId="null" :refresh="queryPrintRecords" />
        </div>
      </a-row>

      <!-- 表格 -->
      <a-table
        :scroll="{ x: 800, y: 500 }"
        :dataSource="tableData"
        :columns="columns"
        rowKey="id"
        :loading="tableLoading"
        :pagination="false"
        @resizeColumn="handleResizeColumn"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'fileName'">
            <a @click="handleDownload(record)">{{ text }}</a>
          </template>
          <template v-if="column.dataIndex === 'createIp'">
            <a-tag v-if="text === 'SUCCESS'" color="#87d068">打印成功</a-tag>
            <a-tag v-if="text === 'FAILED'" color="#f50">打印失败</a-tag>
            <a-tag v-if="text === 'PENDING'" color="#faad14">等待打印</a-tag>
          </template>
          <template v-if="column.dataIndex === 'createTime'">
            {{ formatDate(text) }}
          </template>
          <template v-if="column.dataIndex === 'fileSize'">
            {{ formatFileSize(text) }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a @click="handleDownload(record)">
              <DownloadOutlined /> 下载
            </a>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="smart-query-table-page">
        <div class="pagination-container">
          <a-pagination
            :showSizeChanger="false"
            showQuickJumper
            show-less-items
            v-model:current="queryForm.pageNum"
            :pageSize="queryForm.pageSize"
            :total="total"
            @change="handlePageChange"
            :show-total="(total) => `共${total}条`"
          />

          <div class="page-size-input">
            <span class="page-size-text">每页条数：</span>
            <a-input-number
              v-model:value="customPageSize"
              :min="1"
              :max="100"
              :precision="0"
              style="width: 100px"
              placeholder="输入条数"
              @change="handlePageSizeChange"
            />
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup>
  import { reactive, ref, onMounted, watch } from 'vue';
  import { docmentaApi } from '/@/api/business/file/docment-api.js';
  import TableOperator from '/src/components/support/table-operator/index.vue';
  import { useRouter, useRoute } from 'vue-router';
  import {
    PrinterOutlined,
    ReloadOutlined,
    DownloadOutlined,
    ClearOutlined,
    SearchOutlined
  } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import FileUpload from '/src/components/support/file-upload/index.vue';
  import { FILE_FOLDER_TYPE_ENUM } from '/src/constants/support/file-const.js';
  import { fileApi } from '/@/api/support/file-api.js';

  // 路由实例
  const router = useRouter();
  const route = useRoute();

  // 表单实例
  const printFormRef = ref(null);

  // ---------------------------- 打印功能相关 ----------------------------
  // 文件列表 - 用于FileUpload组件
  const fileList = ref([]);
  // 上传的文件信息
  const uploadedFile = ref(null);
  // 打印机列表
  const printerList = ref([]);
  // 加载状态
  const loadingPrinters = ref(false);
  const printing = ref(false);

  // 打印表单数据
  const printForm = reactive({
    printerId: null,
    copies: 1,
    file: null,
    fileKey: null,
    fileUrl: null
  });

  // 处理文件上传成功
  const handleFileUpload = (files) => {
    if (files && files.length > 0) {
      // 保存上传的文件信息
      const file = files[0];
      uploadedFile.value = file;
      printForm.file = file;
      printForm.fileKey = file.fileKey;
      printForm.fileUrl = file.fileUrl;

      // 更新文件列表显示
      fileList.value = [...files];

      // 手动触发文件字段验证
      if (printFormRef.value) {
        printFormRef.value.validateFields(['file']).catch(() => {});
      }
    } else {
      // 清空文件信息
      uploadedFile.value = null;
      printForm.file = null;
      printForm.fileKey = null;
      printForm.fileUrl = null;
      fileList.value = [];
    }
  };

  // 获取打印机列表
  const getPrinters = async () => {
    try {
      loadingPrinters.value = true;
      const res = await docmentaApi.printList();
      printerList.value = res.data || [];
    } catch (error) {
      console.error('获取打印机列表失败:', error);
      message.error('获取打印机列表失败，请稍后重试');
    } finally {
      loadingPrinters.value = false;
    }
  };

  // 表单提交处理
  const handleSubmit = async () => {
    // 先进行表单验证
    if (!printFormRef.value) return;

    try {
      // 验证所有字段
      await printFormRef.value.validateFields();

      // 验证通过，执行打印逻辑
      await handlePrint();
    } catch (error) {
      // 验证失败，不执行打印
      console.log('表单验证失败:', error);
      message.warning('请完善表单信息后再提交');
    }
  };

  // 处理打印
  const handlePrint = async () => {
    try {
      printing.value = true;

      // 构建JSON格式参数
      const requestData = {
        fileKey: printForm.fileKey,
        printerId: printForm.printerId,
        copies: printForm.copies
      };

      // 调用打印API
      const response = await docmentaApi.printNoRole(requestData);

      // 清空表单
      fileList.value = [];
      uploadedFile.value = null;
      printForm.file = null;
      printForm.fileKey = null;
      printForm.fileUrl = null;
      printForm.printerId = null;
      printForm.copies = 1;

      // 重置表单验证状态
      if (printFormRef.value) {
        printFormRef.value.resetFields();
      }

      // 刷新打印记录
      queryPrintRecords();

      // if (response.success) {
      //   message.success('打印任务已提交');
      //   // 清空表单
      //   fileList.value = [];
      //   uploadedFile.value = null;
      //   printForm.file = null;
      //   printForm.fileKey = null;
      //   printForm.fileUrl = null;
      //   printForm.printerId = null;
      //   printForm.copies = 1;
      //
      //   // 重置表单验证状态
      //   if (printFormRef.value) {
      //     printFormRef.value.resetFields();
      //   }
      //
      //   // 刷新打印记录
      //   queryPrintRecords();
      // } else {
      //   message.error(response.message || '打印任务提交失败');
      // }
    } catch (error) {
      console.error('提交打印任务失败:', error);
      message.error('提交打印任务失败，请稍后重试');
    } finally {
      printing.value = false;
    }
  };

  // ---------------------------- 打印记录和搜索相关 ----------------------------

  // 查询表单
  const queryForm = reactive({
    pageNum: 1,
    pageSize: 20,
  });

  // 搜索表单
  const searchForm = reactive({
    createBy: '',  // 打印人
    fileName: ''   // 文件名称
  });

  // 自定义每页大小
  const customPageSize = ref(queryForm.pageSize);

  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);
  // 表格加载状态
  const tableLoading = ref(false);

  // 表格列定义
  const columns = ref([
    {
      title: '文件名称',
      dataIndex: 'fileName',
      key: 'fileName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '文件类型',
      dataIndex: 'fileType',
      key: 'fileType',
      width: 100,
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 80,
    },
    {
      title: '打印机',
      dataIndex: 'printName',
      key: 'printName',
      width: 100,
    },
    {
      title: '打印份数',
      dataIndex: 'printNum',
      key: 'printNum',
      width: 80,
    },
    {
      title: '打印人',
      dataIndex: 'createBy',
      key: 'createBy',
      width: 100,
    },
    {
      title: '打印IP',
      dataIndex: 'createIp',
      key: 'createIp',
      width: 100,
    },
    {
      title: '打印时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
    },
  ]);

  // 格式化文件大小
  function formatFileSize(size) {
    if (!size) return '';
    const units = ['B', 'KB', 'MB', 'GB'];
    let unitIndex = 0;
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }
    return `${size.toFixed(2)} ${units[unitIndex]}`;
  }

  // 监听pageSize变化
  watch(
    () => queryForm.pageSize,
    (newVal) => {
      customPageSize.value = newVal;
    }
  );

  // 处理分页变化
  function handlePageChange(pageNum) {
    queryForm.pageNum = pageNum;
    queryPrintRecords();
  }

  // 处理每页大小变更
  function handlePageSizeChange(value) {
    if (value && value !== queryForm.pageSize) {
      queryForm.pageSize = value;
      queryForm.pageNum = 1;
      queryPrintRecords();
    }
  }

  // 处理搜索
  function handleSearch() {
    queryForm.pageNum = 1; // 搜索时重置到第一页
    queryPrintRecords();
  }

  // 重置搜索条件
  function resetSearch() {
    searchForm.createBy = '';
    searchForm.fileName = '';
    queryForm.pageNum = 1;
    queryPrintRecords();
  }

  // 查询打印记录（包含搜索条件）
  async function queryPrintRecords() {
    tableLoading.value = true;
    try {
      // 合并查询条件和搜索条件
      const params = {
        ...queryForm,
        ...searchForm
      };

      const queryResult = await docmentaApi.selectPrint(params);
      tableData.value = queryResult.data.list || [];
      total.value = queryResult.data.total || 0;
    } catch (error) {
      console.error('查询打印记录失败:', error);
      message.error('查询打印记录失败，请稍后重试');
    } finally {
      tableLoading.value = false;
    }
  }

  // 刷新记录
  function refreshRecords() {
    queryForm.pageNum = 1;
    queryPrintRecords();
  }

  // 处理文件下载
  function handleDownload(file) {
    if (!file || !file.docmentSrc) {
      message.warning('文件标识不存在，无法下载');
      return;
    }
    try {
      // 使用fileApi的下载方法
      fileApi.downLoadFile(file.docmentSrc);
      message.success('正在准备下载文件');
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败，请稍后重试');
    }
  }

  // 格式化日期
  function formatDate(dateString) {
    if (!dateString) return '';
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  }

  // 处理列宽调整
  function handleResizeColumn(w, col) {
    col.width = w;
  }

  // 页面挂载时初始化
  onMounted(() => {
    // 获取打印机列表
    getPrinters();

    // 从路由参数中获取分页信息
    const { pageNum, pageSize } = route.query;
    if (pageNum) {
      queryForm.pageNum = Number(pageNum);
    }
    if (pageSize) {
      queryForm.pageSize = Number(pageSize);
      customPageSize.value = Number(pageSize);
    }

    // 查询打印记录
    queryPrintRecords();
  });
</script>

<style scoped>
  .print-card {
    margin-bottom: 20px;
    padding: 20px;
  }

  .print-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #1890ff;
  }

  .print-form {
    margin-top: 16px;
  }

  .upload-hint {
    margin-top: 8px;
    font-size: 12px;
    color: #666;
  }

  .print-button-col {
    display: flex;
    align-items: flex-end;
  }

  .print-button {
    width: 100%;
  }

  .record-card {
    padding: 20px;
  }

  .smart-table-btn-block {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
  }

  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
  }

  .page-size-input {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .page-size-text {
    color: rgba(0, 0, 0, 0.65);
  }

  /* 搜索区域样式优化 */
  .ant-input {
    width: 100%;
  }
</style>
